package cn.gov.pbc.dream.util;

import lombok.extern.slf4j.Slf4j;
import sun.java2d.pipe.SpanShapeRenderer;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

@Slf4j
public class DateTimeUtil {

    public final static String DEFAULT_DATE_TIME_FORMAT = "yyyyMMdd";

    public final static String DASH_DATE_FORMAT = "yyyy-MM-dd";

    public final static String DASH_MONTH = "yyyy-MM";

    public final static String FULL = "yyyy-MM-dd HH:mm:ss";

    public static String dateToStr(Date date, String formatStr) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        return formatter.format(date);
    }

    public static Date strToDate(String str) {
        return DateTimeUtil.strToDate(str, DEFAULT_DATE_TIME_FORMAT);
    }

    public static Date strToDate(String value, String formatStr) {
        DateFormat format = new SimpleDateFormat(formatStr);
        format.setTimeZone(TimeZone.getTimeZone("UTC"));

        Date date = null;
        try {
            date = format.parse(value);
        } catch (ParseException e) {
            e.printStackTrace();
            log.error("日期格式转换错误", e);
            return null;
        }
        return date;
    }

    public static String getLastMonth(String month) {
        Date date = DateTimeUtil.strToDate(month, DateTimeUtil.DASH_MONTH);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        date = calendar.getTime();
        return dateToStr(date, DateTimeUtil.DASH_MONTH);
    }
}
